(function($){
	$(window).load(function(){
		var
			oBox     = $('#box'),
			iClientW = $(this).width(),
			iClientH = $(this).height();
		
		var
			iFirstW    = $('.panel:first').width(),
			iFirstImgW = $('img:first').width(),
			iCol       = Math.floor(iClientW/iFirstW),
			aPanel     = $('.panel'),
			aColH      = [],
			bBtn       = true;
		oBox.css('width',iFirstW*iCol);
		
		//设置图片位置
		setPanelPos(aPanel);
		
		//滚动加载新的数据
		$(window).scroll(function(){
			var
				oLast    = $('.panel:last'),
				oLastH   = oLast.offset().top+oLast.height()/2,
				iScrollT = $(window).scrollTop();
			if(bBtn&&iScrollT+iClientH>oLastH){
				$.ajax({
					url:'waterfall.txt',
					type:'GET',
					dataType:'json',
					beforeSend:function(){
						bBtn=false;
					},
					success:function(data){
						for(var i=0;i<data.length;i++){
							var oImg=document.createElement('img');
							$(oImg).attr('src',data[i].src).width(iFirstImgW).height(iFirstImgW*data[i].height/data[i].width);
							var oA=document.createElement('a');
							var oNewPanel=document.createElement('div');
							$(oNewPanel).addClass('panel').css({
								left:(iClientW-iFirstW)/2,
								top:iClientH+iScrollT
							});
							$(oA).append(oImg);
							$(oNewPanel).append(oA);
							oBox.append(oNewPanel);
							
							var iMinK = getColMinKey();
							$(oNewPanel).animate({
								left:iMinK*iFirstW,
								top:aColH[iMinK]
							},1000);
							
							aColH[iMinK] += $(oNewPanel).height();
						}
					},
					complete:function(){
						bBtn=true;
					}
				});
			}
		});
		
		//循环设置图片的left和top值
		function setPanelPos(aPos){
			for(var i=0;i<aPos.length;i++){
				var oPos = aPos.eq(i);
				if(i<iCol){
					oPos.css({top:0,left:i*iFirstW});
					aColH.push(oPos.height());
				}else{
					var iMinK = getColMinKey();
					oPos.css({top:aColH[iMinK],left:iMinK*iFirstW});
					
					//更新高度
					aColH[iMinK] += oPos.height();
				}
			}
		}
		
		//计算列最小高度key
		function getColMinKey(){
			var iMinH = Math.min.apply('null',aColH);
			var iMinK = 0;
			for(var i=0;i<aColH.length;i++){
				if(aColH[i]===iMinH){
					iMinK=i;
					break;
				}
			}
			return iMinK;
		}
	});
})(jQuery);
